package com.everflourish.yeah100.act.questionlib;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.QuestionUploadAdapter;
import com.everflourish.yeah100.entity.question.QuestionTopic;
import com.everflourish.yeah100.entity.question.QuestionUploadImage;
import com.everflourish.yeah100.http.HttpURL;
import com.everflourish.yeah100.http.QuestionRequest;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.CommonUtil;
import com.everflourish.yeah100.utils.ImageSelectHolder;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.PaperType;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/22.
 * 时间：2016/7/22
 */
public class QuestionUploadActivity extends BaseActivity {

    private Toolbar mToolBar;
    private LoadDialog mLoadDialog;
    private RecyclerView mQuestionUploadLv;
    private QuestionUploadAdapter mAdapter;
    private String mExaminationId;
    private Bitmap mUploadBitmap;
    private Uri croUrl;
    private ImageView mUploadIv;
    public QuestionRequest mRequest;
    private List<QuestionTopic> mList;
    private String uploadNo;
    public static String TOPIC_NO_BEGIN = "";
    public static String TOPIC_NO_END = "";
    public static String TOPIC_TYPE = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_upload);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mList = new ArrayList<QuestionTopic>();
        mRequest = QuestionRequest.getInstance();
        mExaminationId = getIntent().getStringExtra(IntentUtil.EXAMINATION_ID);
        croUrl = getIntent().getParcelableExtra(IntentUtil.QUESTION_UPLOAD_URL);
        try {
            mUploadBitmap = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(croUrl));
            ImageSelectHolder.isDisable = true;
            if (ImageSelectHolder.mTempFile != null && ImageSelectHolder.mTempFile.exists()) {
                ImageSelectHolder.mTempFile.delete();
            }
            if (croUrl != null) {
                File cropFile = new File(croUrl.getPath());
                if (cropFile != null && cropFile.exists()) {
                    cropFile.delete();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mAdapter = new QuestionUploadAdapter(mContext, mList, mUploadBitmap);
    }

    private void initView() {
//        mUploadIv = (ImageView) findViewById(R.id.question_upload_iv);
        mQuestionUploadLv = (RecyclerView) findViewById(R.id.question_topic_select);
        mQuestionUploadLv.setAdapter(mAdapter);
        mQuestionUploadLv.setLayoutManager(new LinearLayoutManager(this));
        mToolBar = (Toolbar) findViewById(R.id.toolbar_question_upload);
        mToolBar.setTitle("上传题目");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
        mToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.question_upload_summit:
                        try {
                            if (TOPIC_NO_BEGIN.equals("")) {
                                MyToast.showShort(mContext, "请选择题号");
                            } else {
                                if (!TOPIC_NO_END.equals("")) {
                                    int beginNo = Integer.valueOf(TOPIC_NO_BEGIN);
                                    int endNo = Integer.valueOf(TOPIC_NO_END);
                                    if (beginNo > endNo) {
                                        uploadNo = TOPIC_NO_END + "-" + TOPIC_NO_BEGIN;
                                    } else {
                                        uploadNo = TOPIC_NO_BEGIN + "-" + TOPIC_NO_END;
                                    }
                                } else {
                                    uploadNo = TOPIC_NO_BEGIN;
                                }
                                uploadImage(mUploadBitmap);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
                return true;
            }
        });
    }

    private void configView() {
        getQuestionNosRequest();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void getQuestionNosRequest() {
        JsonObjectRequest request = mRequest.getQuestionNosRequest(mExaminationId, PaperType.NONE,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getQuestionNosListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取题号失败");
                    }
                });
        mQueue.add(request);
    }

    private void getQuestionNosListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.QUESTIONTOPIC);
                Gson gson = new Gson();
                Type type = new TypeToken<List<QuestionTopic>>() {
                }.getType();
                List<QuestionTopic> topicList = gson.fromJson(
                        jsonArray.toString(), type);
                if (topicList == null || topicList.size() == 0) {
                    MyToast.showShort(mContext, "还没设置题型，请设置题型后再上传");
                    mList.clear();
                } else {
                    mList.addAll(topicList);
                }
                mAdapter.notifyDataSetChanged();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09141_000001E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09142_300001E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091499_999999E);
            } else {
                MyToast.showShort(mContext, "获取题号失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "获取题号失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 上传图片
     *
     * @param bitmap
     * @throws Exception
     */
    public void uploadImage(Bitmap bitmap) throws Exception {
        String name = Yeah100.loginInfo.userInfo.name;
        String encoderName = CommonUtil.string2MD5(name);
        final File file = new File(Environment.getExternalStorageDirectory()
                + "/" + encoderName + "_" + System.currentTimeMillis() + ".jpg");
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        RequestParams params = new RequestParams();
        params.addHeader("tokenId", Yeah100.loginInfo.tokenId);
        HttpUtils httpUtils = new HttpUtils();
        String http = new HttpURL().URL_NEW_QUESTION_UPLOAD;
        params.addBodyParameter("outputStream", file);
        params.addBodyParameter("examinationId", mExaminationId);
        httpUtils.send(HttpMethod.POST, http, params,
                new RequestCallBack<Object>() {
                    @Override
                    public void onLoading(long total, long current,
                                          boolean isUploading) {
                        LogUtil.d(total + ":" + current + ":" + isUploading);
                    }

                    @Override
                    public void onStart() {
                        mLoadDialog = LoadDialog.show(mContext, null, "正在上传...");
                    }

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        if (arg0 != null && arg0.getMessage() != null) {
                            if (arg0.getMessage().contains(
                                    "HttpHostConnectException")) {
                                MyToast.showLong(mContext, "网络已断开");
                            }
                        } else {
                            MyToast.showLong(mContext, "上传图片失败");
                        }
                        LoadDialog.dismiss(mLoadDialog);
                        if (file.exists()) {
                            file.delete();
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<Object> response) {
                        String result = (String) response.result;
                        String resultCode = "";
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            resultCode = jsonObject
                                    .getString(Constant.RESULT_CODE);
                            if (resultCode
                                    .equals(ResultCode.result_ok.resultCode)) {
                                String orinImageUrl = jsonObject
                                        .getString("imageUrl");
                                if (StringUtil.stringIsNull(orinImageUrl)) {
                                    MyToast.showShort(mContext, "上传图片失败");
                                    return;
                                }
                                questionUpLoadImageCutRequest(setUploadImagePara(mUploadBitmap, orinImageUrl));
                            } else if (resultCode
                                    .equals(ResultCode.result_000001E.resultCode)) {
                                MyToast.showShort(mContext, R.string.questionlib_09131_000001E);
                            } else if (resultCode
                                    .equals(ResultCode.result_300001E.resultCode)) {
                                MyToast.showShort(mContext, R.string.questionlib_09132_300001E);
                            } else if (resultCode
                                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                                MyToast.showShort(mContext, R.string.questionlib_091399_999999E);
                            } else {
                                MyToast.showShort(mContext, "上传图片失败");
                            }
                        } catch (JSONException e) {
                            LogUtil.e("JSON异常", e);
                            MyToast.showShort(mContext, "上传图片失败");
                        } finally {
                            if (file.exists()) {
                                file.delete();
                            }
                            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                                LoadDialog.dismiss(mLoadDialog);
                            }
                        }
                    }
                });
    }

    /**
     * 设置图片增加参数
     *
     * @param bitmap
     * @param orinImageUrl
     * @return
     */
    private QuestionUploadImage setUploadImagePara(Bitmap bitmap, String orinImageUrl) {
        QuestionUploadImage questionUploadImage = new QuestionUploadImage();
        questionUploadImage.setExaminationId(mExaminationId);
        questionUploadImage.setSeqNo(uploadNo);
        questionUploadImage.setPaperType(PaperType.NONE);
        questionUploadImage.setCompressWidth(bitmap.getWidth());
        questionUploadImage.setWidth(bitmap.getWidth());
        questionUploadImage.setHeight(bitmap.getHeight());
        questionUploadImage.setLeftMargin(0);
        questionUploadImage.setTopMargin(0);
        questionUploadImage.setImageUrl(orinImageUrl);
        questionUploadImage.setQuestionType(1);
        questionUploadImage.setRole(Yeah100.mRoleEnum.name);
        return questionUploadImage;
    }

    /**
     * 题目上传请求
     *
     * @param questionUploadImage
     */
    private void questionUpLoadImageCutRequest(QuestionUploadImage questionUploadImage) {
        JsonObjectRequest request = mRequest.questionUpLoadImageCutRequest(questionUploadImage,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        questionUpLoadImageCutListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "上传题目失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 题目增加图片监听
     *
     * @param response
     */
    private void questionUpLoadImageCutListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                String cropImageUrl = response.getString("imageUrl");
                if (StringUtil.stringIsNull(cropImageUrl)) {
                    MyToast.showLong(mContext, "上传题目失败");
                    return;
                }
                finishActivity();
                MyToast.showShort(mContext, "上传成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09121_000001E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09122_300001E);
            } else if (resultCode.equals(ResultCode.result_300024E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09123_300024E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091299_999999E);
            } else {
                MyToast.showShort(mContext, "上传题目失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "上传题目失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    private void finishActivity() {
        TOPIC_NO_BEGIN = "";
        TOPIC_NO_END = "";
        TOPIC_TYPE = "";
        Intent resultIntent = getIntent();
        this.setResult(RESULT_OK, resultIntent);
        IntentUtil.finishActivity(QuestionUploadActivity.this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_question_upload, menu);
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}
